package com.ruoyi.libb.utlis;

import com.ruoyi.libb.utils.Result;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class ActivitiUtil {

    /**
     * 流程部署
     */
    public HashMap<String, Object> createDeployment(RepositoryService repositoryService,String bpmn,String name) {
        //部署对象
        String fileName = bpmn;
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource(fileName)
                .name(name)
                .deploy();
        System.out.println("流程部署名称：" + deployment.getName());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", deployment.getId());
        hashMap.put("key", deployment.getKey());
        hashMap.put("name", deployment.getName());
        return hashMap;
    }

    /**
     * 获取流程定义的列表
     *
     * @return
     */
    public List<HashMap<String, Object>> getDeployment(RepositoryService repositoryService){
        List<ProcessDefinition> list = repositoryService
                .createProcessDefinitionQuery()
                //按照版本号进行降序排序
                .orderByProcessDefinitionVersion().desc()
                //输出list列表
                .list();
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();
        for (ProcessDefinition processDefinition : list) {
            HashMap<String, Object> hashMap = new LinkedHashMap<>();
            //System.out.println("------------------------");
            //System.out.println("流程部署id ：" + processDefinition.getDeploymentId());
            //System.out.println("流程定义id：" + processDefinition.getId());
            //System.out.println("流程定义名称：" + processDefinition.getName());
            //System.out.println("流程定义key：" + processDefinition.getKey());
            //System.out.println("流程定义版本：" + processDefinition.getVersion());
            hashMap.put("deploymentId", processDefinition.getDeploymentId());
            hashMap.put("id", processDefinition.getId());
            hashMap.put("name", processDefinition.getName());
            hashMap.put("key", processDefinition.getKey());
            hashMap.put("version", processDefinition.getVersion());
            hashMapList.add(hashMap);
        }
        return hashMapList;
    }

    /**
     * 流程状态变更（挂起，启用）流程定义中所有的流程实例
     * @param repositoryService
     * @param id
     */
    public void updateDeployment(RepositoryService repositoryService, String id){

        //挂起
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .processDefinitionId(id).singleResult();

        //是否暂停
        boolean suspend = processDefinition.isSuspended();

        if(suspend){
            //如果暂停则激活，这里将流程定义下的所有流程实例全部激活
            repositoryService.activateProcessDefinitionById(id, true, null);
        }else{
            //如果激活则挂起，这里将流程定义下的所有流程实例全部挂起
            repositoryService.suspendProcessDefinitionById(id, true, null);
            System.out.println("流程定义："+id+"挂起");
        }
    }

    /**
     * 流程实例列表
     * @param runtimeService
     * @param key 流程的key
     */
    public List<HashMap<String,Object>> getRuntime(RuntimeService runtimeService, String key){

        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(key)
                .orderByProcessInstanceId()
                .desc()
                .list();

        List<HashMap<String,Object>> hashMapList = new ArrayList<>();

        for (ProcessInstance processInstance : list) {
            //System.out.println("----------------------------");
            //System.out.println("流程实例id：" + processInstance.getProcessInstanceId());
            ////System.out.println("所属流程定义id：" + processInstance.getProcessDefinitionId());
            //System.out.println("所属流程定义：" + processInstance.getProcessDefinitionName());
            //System.out.println("是否执行完成：" + processInstance.isEnded());
            //System.out.println("是否暂停：" + processInstance.isSuspended());

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("processInstanceId", processInstance.getProcessInstanceId());
            hashMap.put("processDefinitionName", processInstance.getProcessDefinitionName());
            hashMap.put("businessKey", processInstance.getBusinessKey());
            hashMap.put("isEnded", processInstance.isEnded());
            hashMap.put("isSuspended", processInstance.isSuspended());

            hashMapList.add(hashMap);

        }

        return hashMapList;

    }

    /*
     * 查询流程实例(通过实例id查询)
     * @param runtimeService
     * @param key 流程实例的id
     */
    public HashMap<String,Object> getRuntimeById(RuntimeService runtimeService, String id){

        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery()
                .processInstanceId(id).list();

        if(list == null){
            return null;
        }

        ProcessInstance processInstance = list.get(0);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("processInstanceId", processInstance.getProcessInstanceId());
        hashMap.put("processDefinitionName", processInstance.getProcessDefinitionName());
        hashMap.put("businessKey", processInstance.getBusinessKey());
        hashMap.put("isEnded", processInstance.isEnded());
        hashMap.put("isSuspended", processInstance.isSuspended());

        return hashMap;

    }

    /*
     * 查询流程实例(通过业务id（业务标识）查询)
     * @param runtimeService
     * @param key 流程实例的id
     */
    public HashMap<String,Object> getRuntimeByBusinessKey(RuntimeService runtimeService, String businessKey){

        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(businessKey).list();

        if(list == null){
            return null;
        }

        ProcessInstance processInstance = list.get(0);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("processInstanceId", processInstance.getProcessInstanceId());
        hashMap.put("processDefinitionName", processInstance.getProcessDefinitionName());
        hashMap.put("businessKey", processInstance.getBusinessKey());
        hashMap.put("isEnded", processInstance.isEnded());
        hashMap.put("isSuspended", processInstance.isSuspended());

        return hashMap;

    }


    /**
     * 创建流程实例
     * @param runtimeService
     * @param key 流程的key
     *
     *         HashMap<String, Object> hashMap = new HashMap<>();
     *         hashMap.put("username", "李鹏");
     */
    public void createRuntime(RuntimeService runtimeService, String key, String businessKey, HashMap<String, Object> hashMap){

        if(hashMap != null){
            runtimeService.startProcessInstanceByKey(key, businessKey, hashMap);
        }else{
            runtimeService.startProcessInstanceByKey(key, businessKey);
        }


    }

    /**
     * 流程状态变更（挂起，启用）单个流程实例
     * @param id    流程实例id
     * @param definitionId  流程定义id
     * @param key   key
     * @return
     */
    public void updateRuntime(RuntimeService runtimeService, String id, String definitionId, String key){
        //获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(id).singleResult();

        //是否暂停
        boolean suspend = processInstance.isSuspended();

        if(suspend){
            //如果暂停则激活
            runtimeService.activateProcessInstanceById(id);
            System.out.println("流程实例："+id+"激活");
        }else{
            //如果激活则挂起
            runtimeService.suspendProcessInstanceById(id);
            System.out.println("流程实例："+id+"挂起");
        }

    }

    /**
     * 流程中任务列表
     * @param pid   流程实例id
     * @param key   流程key
     * @return
     */
    public List<HashMap<String, Object>> getTask(RuntimeService runtimeService, TaskService taskService, String pid, String key){
        List<Task> list = taskService.createTaskQuery()//
                .processDefinitionKey(key)//
                .processInstanceId(pid)
                .includeProcessVariables().list();

        List<HashMap<String, Object>> hashMapList = new ArrayList<>();

        for (Task task : list){
            System.out.println("流程实例id：" + task.getProcessInstanceId());
            System.out.println("任务id：" + task.getId());
            System.out.println("任务负责人：" + task.getAssignee());
            System.out.println("任务名称：" + task.getName());

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", task.getId());
            hashMap.put("processInstanceId", task.getProcessInstanceId());
            hashMap.put("assignee", task.getAssignee());
            hashMap.put("name", task.getName());
            //            获取当前审批的实例内容
            HashMap<String, Object> runtimeShow = getRuntimeById(runtimeService, task.getProcessInstanceId());
            hashMap.put("processDefinitionName", runtimeShow.get("processDefinitionName"));
            hashMap.put("businessKey", runtimeShow.get("businessKey"));
            hashMap.put("createTime", task.getCreateTime());
            hashMapList.add(hashMap);
        }

        return hashMapList;

    }

    /**
     * 按照审批人查询当前用户所拥有任务（所需要处理的任务）
     * @param taskService
     * @param name
     * @return
     */
    public List<HashMap<String, Object>> getTaskByName(RuntimeService runtimeService, TaskService taskService, String name){
        List<Task> list = taskService.createTaskQuery()
                .taskAssignee(name)
                .includeProcessVariables().list();
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();

        for (Task task : list){
            System.out.println("流程实例id：" + task.getProcessInstanceId());
            System.out.println("任务id：" + task.getId());
            System.out.println("任务负责人：" + task.getAssignee());
            System.out.println("任务名称：" + task.getName());

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", task.getId());
            hashMap.put("processInstanceId", task.getProcessInstanceId());
            hashMap.put("assignee", task.getAssignee());
            hashMap.put("name", task.getName());

//            获取当前审批的实例内容
            HashMap<String, Object> runtimeShow = getRuntimeById(runtimeService, task.getProcessInstanceId());
            hashMap.put("processDefinitionName", runtimeShow.get("processDefinitionName"));
            hashMap.put("businessKey", runtimeShow.get("businessKey"));

            hashMap.put("createTime", task.getCreateTime());
            hashMapList.add(hashMap);
        }

        return hashMapList;

    }



    /**
     * 完成任务
     * @param taskService
     * @param id 任务节点id
     * @return
     */

    public Boolean taskUpdate(TaskService taskService, String id){
        Boolean msg = true;
        try {
            taskService.complete(id);
        }catch (Exception e){
            e.printStackTrace();
            e.getMessage().toString();
            msg = false;
        }
        return msg;
    }

    public Boolean taskRun(TaskService taskService, String id,String pass){
        Boolean msg = true;
        try {
            Task task = taskService.createTaskQuery().taskId(id).singleResult();
            if (task!=null){
                taskService.setVariableLocal(task.getId(),"pass",pass);
                taskService.complete(task.getId());
                System.out.println("执行成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            e.getMessage().toString();
            msg = false;
        }
        return msg;
    }

    /**
     * 取消任务
     */
    public Boolean unclaimTaks(TaskService taskService, String id){
        Boolean msg = true;
        try {
            taskService.unclaim(id);
        }catch (Exception e){
            e.printStackTrace();
            e.getMessage().toString();
            msg = false;
        }
        return msg;
    }

    /**
     * 任务的删除
     */
    public Boolean delTaks(RuntimeService runtimeService, String id,String message){
        Boolean msg = true;
        try {
            runtimeService.deleteProcessInstance(id,message);
        }catch (Exception e){
            e.printStackTrace();
            e.getMessage().toString();
            msg = false;
        }
        return msg;
    }

    /**
     * 历史活动查询
     * @param historyService
     * @return
     */
    public String historySelectList(HistoryService historyService){
        List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery()
                .finished().list();

        historicActivityInstanceList.forEach(historicActivityInstance -> {
            System.out.println("---------------------------------------------------");
            System.out.println("当前激活ID:" + historicActivityInstance.getActivityId());
            System.out.println("当前激活名称:" + historicActivityInstance.getActivityName());
            System.out.println("流程定义ID:" + historicActivityInstance.getProcessDefinitionId());
            System.out.println("流程实例ID:" + historicActivityInstance.getProcessInstanceId());
            System.out.println("办理人:" + historicActivityInstance.getAssignee());
            System.out.println("开始时间:" + historicActivityInstance.getStartTime());
            System.out.println("结束时间:" + historicActivityInstance.getEndTime());
            System.out.println("---------------------------------------------------");
        });

        return "YES";

    }

    /**
     * 历史活动查询
     * @param historyService
     * @param id
     * @return
     */
    public String history(HistoryService historyService, String id){
        List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(id).finished().list();

        historicActivityInstanceList.forEach(historicActivityInstance -> {
            System.out.println("---------------------------------------------------");
            System.out.println("当前激活ID:" + historicActivityInstance.getActivityId());
            System.out.println("当前激活名称:" + historicActivityInstance.getActivityName());
            System.out.println("流程定义ID:" + historicActivityInstance.getProcessDefinitionId());
            System.out.println("流程实例ID:" + historicActivityInstance.getProcessInstanceId());
            System.out.println("办理人:" + historicActivityInstance.getAssignee());
            System.out.println("开始时间:" + historicActivityInstance.getStartTime());
            System.out.println("结束时间:" + historicActivityInstance.getEndTime());
            System.out.println("---------------------------------------------------");
        });

        return "YES";

    }

    /**
     * 历史任务查询
     * @param id 流程实例id
     * @return
     */
    public String historyTask(HistoryService historyService, String id){
        List<HistoricTaskInstance> historicTaskInstanceList = historyService
                .createHistoricTaskInstanceQuery()
                .processInstanceId(id).finished().list();

        for (HistoricTaskInstance value : historicTaskInstanceList){

            System.out.println("---------------------------------------------------");
            System.out.println("任务id:" + value .getId());
            System.out.println("流程实例id:" + value.getProcessInstanceId());
            System.out.println("任务名称:" + value.getName());
            System.out.println("办理人:" + value.getAssignee());
            System.out.println("开始时间:" + value.getStartTime());
            System.out.println("结束时间:" + value.getEndTime());
            System.out.println("---------------------------------------------------");
        }

        return "YES";

    }

    /**
     * 历史查询流程状态
     * @param id 实例id
     * @return
     */
    public String historyType(RuntimeService runtimeService, String id){
        ProcessInstance processInstance = runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(id)
                .singleResult();

        return "YES";

    }

    /**
     * 流程的创建
     */
    public Result ajaxCreateRuntime(RuntimeService runtimeService, String key, String businessKey) {
        ActivitiUtil activitiUtil = new ActivitiUtil();
        HashMap<String, Object> hashMap = new LinkedHashMap<>();
        Approver approverS=new Approver();
        String approver = approverS.getApprover();
        String[] inputsArray = approver.split(",");
        if (inputsArray.length == 0) {
            String[] split = approver.split(":");
            hashMap.put(split[0],split[1]);
            activitiUtil.createRuntime(runtimeService, key, businessKey, hashMap);
            return Result.success();
        }
        int count = inputsArray.length;
        for (int i = 0; i < count; i++) {
            String strings = inputsArray[i];
            String[] a = strings.split(":");
            hashMap.put(a[0], a[1]);
        }

        activitiUtil.createRuntime(runtimeService, key, businessKey, hashMap);

        return Result.success();
    }









}
